<template>
    <el-form ref="form" v-if="model" :validate-on-rule-change="false" v-bind="$attrs" :model="model" :rules="rules">
        <template v-for="(item, index) in options" :key="index">
            <el-form-item v-if="!item.children || !item.children.length" :label="item.label" :prop="item.prop">
                <component v-bind="item.attrs" :is="`el-${item.type}`" v-model="model[item.prop!]"></component>
            </el-form-item>
            <el-form-item v-if="item.children && item.children.length" :label="item.label" :prop="item.prop" >
                <component v-bind="item.attrs" :is="`el-${item.type}`" v-model="model[item.prop!]" :placeholder="item.placeholder">
                    <component
                    v-for="(child,i) in item.children"
                    :is="`el-${child.type}`"
                    v-bind="child.attrs"
                    :key="i"
                    :placeholder="item.placeholder"
                    :label="child.label"
                    :value="child.value"
                    ></component>
                </component>
            </el-form-item>
        </template>
        <el-form-item>
            <slot name="action" :model="model" :form="form"></slot>
        </el-form-item>
        
    </el-form>
</template>

<script lang="ts" setup>
import { PropType, onMounted, ref, watch } from 'vue';
import { FormOptions } from './types/types';
import cloneDeep from 'lodash/cloneDeep'
let props = defineProps({
    options: {
        type: Array as PropType<FormOptions[]>,
        require: true
    }
})
//表单的model实际上是对应el-form-item子项的prop
//如：model={username："",password:""}
let model = ref<any>(null)
let rules = ref<any>(null)
let form=ref(null)
const initForm = () => {
    if (props.options && props.options.length) {
        let m: any = {}
        let r: any = {}
        props.options!.map((item: FormOptions) => {
            r[item.prop!] = item.rules
            m[item.prop!] = item.value

        })
        model.value = cloneDeep(m)
        rules.value = cloneDeep(r)
        console.log(model.value)
        console.log(rules.value)
    }
}
watch(()=>props.options,()=>{
    initForm()
},{deep:true})
onMounted(() => {
    initForm()
})
</script>
<style lang="scss" scoped></style>
